import qs from 'qs'
import axios from 'axios'

axios.defaults.timeout = 0
// axios.defaults.baseURL = ''

//http request 拦截器
axios.interceptors.request.use(config => {
    // const token = getCookie('名称');注意使用的时候需要引入cookie方法，推荐js-cookie

    if ($Utils.isNull(config.headers)) {
      config.headers = {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    }
    config.transformRequest = [function(data) {
      try {
        data['SessionID'] = localStorage.getItem('SessionId')
        let userInfo = $Utils.getUserInfo()
        if (!$Utils.isNull(data['data'])) {
          let params = data['data']
          params = { ...params, ...userInfo }
          data['data'] = JSON.stringify(params)
        } else {
          data['data'] = JSON.stringify(userInfo)
        }
        if (!$Utils.isNull(data['query_inputdata'])) {
          let params = data['query_inputdata']
          params = { ...params, ...userInfo }
          data['query_inputdata'] = JSON.stringify(params)
        }
        if (!$Utils.isNull(data['XmlData'])) {
          let params = data['XmlData']
          params = { ...params, ...userInfo }
          data['XmlData'] = JSON.stringify(params)
        }
        if (!$Utils.isNull(data['json'])) {
          data['json'] = JSON.stringify(data['json'])
        }
      } catch (e) {
      }
      if (data instanceof FormData) {
        return data
      }
      return qs.stringify(data)
    }]
    return config
  },
  error => {
    return Promise.reject(err)
  }
)

//http response 拦截器
axios.interceptors.response.use(
  response => {
    let err_msg
    if (!(response.data instanceof Object)) {
      err_msg = response.data
    }
    if ($Utils.isNull(err_msg) && response.data.MSGID == 'E') {
      err_msg = response.data.MESSAGE
    }
    if (!$Utils.isNull(err_msg)) {
      $Utils.toast({
        message: err_msg,
        duration: 4000,
        position: 'top'
      })
      throw new Error(err_msg)
    }
    return response.data
  },
  error => {
    $Utils.toast({
      message: error,
      duration: 4000,
      position: 'top'
    })
    return Promise.reject(error)
  }
)

/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */

export function get(url, params = {}) {
  return new Promise((resolve, reject) => {
    axios.get(url, {
      params: params
    }).then(response => {
      resolve(response)
    }).catch(err => {
      reject(err)
    })
  })
}


/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function post(url, data = {}, config = {}) {
  return new Promise((resolve, reject) => {
    axios.post(url, data || {}, config).then(response => {
      resolve(response)
    }).catch(err => {
      reject(err)
    })
  })
}


/**
 * Inbound/invoke.do 的封装
 * @param interfaceId
 * @param params
 * @returns {Promise<any>}
 */
export function api(interfaceId, params = {}) {
  let requestParams = { interfaceId: interfaceId, data: params || {} }
  return post('/api/Inbound/invoke.do', requestParams)
}

/**
 * /Inbound/api/invoke.do 的封装
 * 主要用于走工作流
 * @param interfaceId
 * @param params
 * @returns {Promise<any>}
 */
export function apiWorkflow(interfaceId, xwbh, params = {}) {
  let userInfo = $Utils.getUserInfo()
  let requestParams = {
    PI_USERNAME: userInfo.PCRM_CZY02,
    xwbh: xwbh,// 工作流行为编号
    interfaceId: interfaceId,// 接口 id
    data: params || {}
  }
  return post('/api/Inbound/api/invoke.do', requestParams)
}

/**
 * /query/api.do 的封装
 * @param query_bean
 * @param params
 * @returns {Promise}
 */
export function query(query_bean, params = {}) {
  let userInfo = $Utils.getUserInfo()
  let requestParams = {
    query_bean: query_bean,
    query_datasource: 'scm',
    query_access_user: userInfo.PCRM_CZY02,
    query_access_company: userInfo.PCRM_GSXX01,
    query_extend_access: true,
    response_compression: 'gzip',
    response_data_format: 'json',
    query_inputdata: params
  }
  return post('/api/query/api.do', requestParams)
}

/**
 * /jlquery/select.do 的封装
 * @param params
 * @returns {Promise}
 */
export function select(params = {}) {
  return new Promise((resolve, reject) => {
    let base = {
      DataBaseType: 'scmform',
      dataType: 'Json',
      QryType: 'Bill'
    }
    params = { ...params, ...base }
    post('/api/jlquery/select.do', { XmlData: params }).then(v => {
      resolve(v['data'])
    }).catch(e => {
      reject(e)
    })
  })
}

/**
 * queryMongo 的封装
 * @param params
 * @returns {Promise}
 */
export function find(collection, params = {}) {
  return new Promise((resolve, reject) => {
    query('mongoQuery', {
      collection: collection,
      query: params
    }).then(v => {
      v.splice(v.length - 1, 1)
      v.forEach(v => delete v._id)
      resolve(v)
    }).catch(e => {
      reject(e)
    })
  })
}

